package com.base.common.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.Map;

public class TokenUtils {

    // 根据角色获取秘钥
    private static Key getKeyByRole(String role) {
        String secret = getSecretByRole(role);
        return Keys.hmacShaKeyFor(secret.getBytes());
    }

    private static String getSecretByRole(String role) {
        switch (role) {
            case TokenConstants.ROLE_PORTAL:
                return TokenConstants.SECRET_PORTAL;
            case TokenConstants.ROLE_ADMIN:
                return TokenConstants.SECRET_ADMIN;
            default:
                throw new IllegalArgumentException("Unknown role: " + role);
        }
    }

    // 生成 Token
    public static String generateToken(String role, Map<String, Object> userMap, long expireMillis) {
        Key key = getKeyByRole(role);
        return Jwts.builder().setClaims(userMap).claim("role", role)
                .setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + expireMillis)).signWith(key, SignatureAlgorithm.HS256).compact();
    }

    // 解析 Token
    public static Claims parseToken(String token, String role) {
        Key key = getKeyByRole(role);

        return Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }
}
